import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {IEvent, IEventHandle} from './EventM';
import {LoginSuccessEvent, LoginSuccessEventHandle} from './LoginSuccessEventHandle';
import {LoginStatusFailureEvent, LoginStatusFailureEventHandle} from './LoginStatusFailureEventHandle';

/**
 * 事件 订阅,产生,下订阅 服务
 */
@Injectable({
  providedIn: 'root'
})
export class EventsService<T extends IEvent> {
  constructor() {
  }

  // 定义一个Subject来存储事件
  private eventSubject = new Subject<T>(); // 创建一个Subject来管理事件

  // 广播事件的方法 //生产事件消息
  broadcastEvent(eventType: T) {
    this.eventSubject.next(eventType);
  }

  // 获取事件的Observable，供订阅使用
  getEventObservable() {
    return this.eventSubject.asObservable();
  }
}

/**
 * 事件分发服务
 */
@Injectable({
  providedIn: 'root'
})
export class EventStrategyDispatcher<T extends IEvent> {
  private handlers: Map<string, IEventHandle<T>> = new Map();

  constructor(private loginSuccessEventHandle: LoginSuccessEventHandle,
              private loginStatusFailureEventHandle: LoginStatusFailureEventHandle
  ) {
    // 注册具体的事件处理器
    console.log("注册LoginSuccessEventHandle>>>", LoginSuccessEvent.name);
    this.handlers.set(LoginSuccessEvent.name, loginSuccessEventHandle);

    console.log("注册LoginStatusFailureEvent>>>", LoginStatusFailureEvent.name);
    this.handlers.set(LoginStatusFailureEvent.name, loginStatusFailureEventHandle);

  }

  //分发消息
  dispatch(event: T): void {
    //从注册缓存中取出handler处理器
    const handler = this.handlers.get(event.eventType);
    if (handler) {
      //调用对应的处理器的处理方法
      handler.handle(event);
    } else {
      console.error(`No handler found for event type: ${event.eventType}`);
      throw new Error(`EventStrategyDispatcher  No handler found for event type: ${event.eventType}`);
    }
  }
}

